package com.gitee.hioove.utils;

import com.hioove.entity.Cat;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class RightAdvice implements MethodInterceptor {
    //代理模式中一定要有目标类的引用
    private Object targetObject;  //注意，这个就是目标类的引用

    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy arg3) throws Throwable {
        String methodName = method.getName();
            //在invoke中加入您要增强的代码
            check();   //前置增强
        //调用目标的对应的方法
        Object returnValue = method.invoke(proxy, args);   // object is not an instance of declaring class
        return returnValue;
    }




    //创建一个方法来完成创建代理对象
    public Object createInstance(Object targetObject) {
        this.targetObject = targetObject;   //  => Object
        Enhancer enhancer = new Enhancer();

        enhancer.setSuperclass((Class) targetObject);
        //enhancer.setClassLoader(   targetObject.getClass().getClassLoader()  );
        enhancer.setCallback(this);

        return enhancer.create();  //创建代理类对象.
    }

    //增强
    private void check() {
        System.out.println("***********************************");
        System.out.println("权限检查");
        System.out.println("***********************************");
    }
    public static void main(String[] args) {
        RightAdvice foregroundColorTest = new RightAdvice();
        Cat cat = (Cat) foregroundColorTest.createInstance(Cat.class);
        cat.shout();
    }
//
//    @Override
//    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
//        return null;
//    }
}
